<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard;

use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Call\Constants\ClientTypeCode;
use MoChat\App\Client\Contract\ClientContract;
use MoChat\App\Client\Model\Client;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\Client\Logic\IndexLogic;
use MoChat\App\Sales\Model\SalesTask;
use MoChat\App\Sales\Model\WorkDepartment;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;

/**
 * 会员编辑.
 * @Controller
 */
class UpdateImport extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     * })
     *
     * @RequestMapping(path="/dashboard/client/updateImport", methods="POST")
     */
    public function handle(): array
    {
        ini_set("max_execution_time", "0");
        ini_set("memory_limit", "3072M");

        $file = $this->request->file('file');
        if (!$file){
            throw new CommonException(ErrorCode::INVALID_PARAMS, '请上传excel文件');
        }
        $extension = $file->getExtension();
        if (!in_array(strtolower($extension), ['xlsx', 'xls'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, 'excel文件格式错误');
        }
        $tmpName = $file->getRealPath();
        if (is_uploaded_file($tmpName)) {
            // 有Xls和Xlsx格式两种
            $objReader = IOFactory::createReader('Xlsx');

            $filename = $tmpName;
            $objPHPExcel = $objReader->load($filename);  //$filename可以是上传的表格，或者是指定的表格
            $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
            $highestRow = $sheet->getHighestRow();       // 取得总行数
            // $highestColumn = $sheet->getHighestColumn();   // 取得总列数

            //定义$usersExits，循环表格的时候，找出已存在的用户。
            $data = [];
            //循环读取excel表格，整合成数组。如果是不指定key的二维，就用$data[i][j]表示。
            for ($j = 2; $j <= $highestRow; $j++) {
                $data[]=[
                    'id' => $objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue(),
                    'service' => $objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue(),
                    'salesperson' => $objPHPExcel->getActiveSheet()->getCell("C" . $j)->getValue(),
                ];
            }
            if (count($data)) {
                foreach ($data as $key => $value){
                    Db::table('client')->where('id', $value['id'])->update([
                        'b2b_salesman_name' => $value['salesperson'],
                        'b2b_manager_name' => $value['service']
                    ]);
                }
            }
        }
        return [];


    }

    /**
     * 验证规则.
     */
    protected function rules(): array
    {
        return [

        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    protected function messages(): array
    {
        return [

        ];
    }
}
